package com.lv.db.control;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.lv.utils.L;
import com.lv.db.entity.LinkMan;

public class DBControl {

	private final String TAG = "DBControl";
	private DBOpenHelper helper;
	private SQLiteDatabase db;
	private boolean isDevelop=true;
	private Context context;
	public DBControl(Context context)
	{
		this.context=context;
		helper = new DBOpenHelper(context);
	}
	public synchronized void exeSQL(String sql) {
		try {
			db = helper.getWritableDatabase();
			L.d(TAG, "exeSQL:"+sql);
			db.execSQL(sql);
		} catch (SQLException e) {
			L.e(TAG, e.toString());
		}
	}

	public synchronized void exeSQL(String sql, Object[] obj) {
		try {
			db = helper.getWritableDatabase();
			
			if(isDevelop) {
				StringBuffer _s=new StringBuffer();
				for(int i=0;i<obj.length;i++){
					_s.append(i+":"+obj[i].toString()).append(",");
				}
				L.d(TAG, "exeSQL:"+sql+" obj:"+_s);
			}
			
			db.execSQL(sql, obj);
		} catch (SQLException e) {
			L.e(TAG, e.toString());
		}
	}

	public synchronized Cursor openDB(String sql) {
		db = helper.getWritableDatabase();
		 L.d(TAG, "find:"+sql);
		Cursor cursor = db.rawQuery(sql, null);
		return cursor;
	}

	public synchronized void closeDB() {
		db = helper.getWritableDatabase();
		if(db.isOpen()) db.close();
	}

	public void beginTransaction() {
		db = helper.getWritableDatabase();
		db.beginTransaction();
	}

	public void endTransaction() {
		db = helper.getWritableDatabase();
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	public boolean isTabExist(String tabName) {
		boolean result = false;
		Cursor cursor = null;
		try {
			if (tabName != null && tabName.trim().length() >= 0) {

				String sql = "SELECT COUNT(*) AS C FROM SQLITE_MASTER WHERE TYPE ='table' AND NAME ='"
						+ tabName.trim() + "' ";
				L.d("DBControl.isTabExist.SQL:", sql);
				cursor = openDB(sql);
				if (cursor != null) {
					if (cursor.moveToNext()) {
						int count = cursor.getInt(0);
						if (count > 0) {
							result = true;
						}
					}
				}
			} else {
				return false;
			}
		} catch (Exception e) {
			if(isDevelop) L.e("DBControl.isTabExist --- error:", e.toString());
		} finally {
			tabName = null;
			cursor.close();
			closeDB();
		}
		return result;
	}

	public void createTable(String tableName, String tableDef) {
		String sSql = "";
		try {
			if (this.isTabExist(tableName)) {
				L.w(TAG, "table [" + tableName + "] is alreay created!");
			} else {
				sSql = tableDef;
				// " CREATE TABLE Sys_Pad_Title (FID INTEGER primary Key autoincrement,FTitleName varchar(50),FSysName varchar(50),FShowName varchar(50),FTable varchar(30)) ";
				this.exeSQL(sSql);
			}
		} catch (Exception e) {
			L.e(TAG, "createTable --->" + e.toString());
		} finally {
			this.closeDB();
		}
	}

	public boolean isColumExist(String tableName, String tableColumn) {
		Cursor cursor = null;
		boolean result = false;
		try {
			String sql = "SELECT * FROM " + tableName + " LIMIT 0 ";
			cursor = this.openDB(sql);
			result = cursor != null && cursor.getColumnIndex(tableColumn) != -1;
			L.d(TAG, "isColumExist.SQL:" + sql);
		} catch (Exception e) {
			L.e(TAG, "isColumExist..." + e.getMessage());
		} finally {
			if (null != cursor && !cursor.isClosed()) {
				cursor.close();
				this.closeDB();
			}
		}
		return result;
	}


	public void create_system_table(){
		LinkMan linkMan=new LinkMan();
		createTable(linkMan.tableName(), linkMan.tableDef());
		if (!this.isColumExist(linkMan.tableName(), linkMan._fspelledall())) {
			String sql = "ALTER TABLE " + linkMan.tableName() + " ADD COLUMN "+linkMan._fspelledall()+" VARCHAR(50) ;";
			this.exeSQL(sql);
			this.closeDB();
		}
		if (!this.isColumExist(linkMan.tableName(), linkMan._fspellsort())) {
			String sql = "ALTER TABLE " + linkMan.tableName() + " ADD COLUMN "+linkMan._fspellsort()+" VARCHAR(50) ;";
			this.exeSQL(sql);
			this.closeDB();
		}


	}

}
